<?php

namespace app\merchants\controller;

use app\common\loader\ModelSystem;
use app\common\validate\merchant\MerchantStatisticValid;
use app\common\validate\system\SystemApiValid;
use app\merchants\loader\Services;
use think\Exception;

class System extends ApiBase
{

    /**
     * 商户信息
     * @return void
     */
    public function info(): void
    {
        try {
            $info = Services::System()->info($this->merId);
            api_result(API_SUCCESS, '请求成功', $info);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 保存商户的设置信息
     * @return void
     */
    public function setting(): void
    {
        try {
            $postData = input('post.');
            validate(SystemApiValid::class)->scene('setting')->check($postData);
            Services::System()->saveSetting($this->merId, $postData);
            api_result(API_SUCCESS, '保存成功');
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 获取商户的库存信息
     * @return void
     */
    public function stock(): void
    {
        try {
            $info = Services::System()->stock($this->merId);
            api_result(API_SUCCESS, '请求成功', $info);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 虚码套餐列表
     * @return void
     */
    public function virtual_package(): void
    {
        try {
            $list = ModelSystem::SystemVirtualPackage()->packageList();
            api_result(API_SUCCESS, '请求成功', $list);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     *  上传文件
     * @return void
     */
    public function upload(): void
    {
        try {
            $info = Services::System()->uploadFile();
            api_result(API_SUCCESS, '请求成功', $info);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 删除文件
     * @return void
     */
    public function delete_file(): void
    {
        try {
            $file = input('post.url', '');
            $info = Services::System()->deleteFile($file);
            api_result(API_SUCCESS, '请求成功', $info);

        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 获取地区信息
     * @login true
     * @hide true
     */
    public function area_list(): void
    {
        try {
            $id = $this->request->get('id/d', 0);
            $list = Services::System()->AreaList($id);
            api_result($list);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 获取授权，跳转授权页面
     */
    public function get_oauth()
    {
        try {
            $params = $this->request->get();
            $params['mer_id'] = $this->adminUser['mer_id'];
            $admin_id = $this->adminUser['admin_id'];
            $model =  Services::System();
            if (isset($params['admin_id']) && !empty($params['admin_id'])) {
                $admin_id = $params['admin_id'];
            }
            $params['admin_id'] = $admin_id;
            $model->checkUser(['mer_id' => $params['mer_id'], 'id' => $params['admin_id']]);
            $result = $model->getOauth($params);
            if (!empty($result['url'])) {
                $result['url'] = domain() . '/qrcode?data=' . base64_encode($result['url']);
            }
            api_result($result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 微信授权绑定OPENID
     */
    public function wx_oauth()
    {
        try {
            $params = $this->request->post();
            if (empty($params['code'])) {
                api_exception(400, 'code不能为空');
            }
            Services::System()->merchantAuth($params);
            api_result(API_SUCCESS, '授权成功');
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 系统日志
     * @return void
     */
    public function system_log()
    {
        try {
            $getData = input('get.');
            $option = $this->formatOption($getData);

            $where[] = ['mer_id', '=', $this->merId];
            $stime = trim($getData['stime'] ?? '');
            $etime = trim($getData['etime'] ?? '');
            if (!empty($stime) && !empty($etime)) {
                $where[] = ['create_at', 'between', [$stime . ' 00:00:00', $etime . ' 23:59:59']];
            } else {
                if (!empty($stime)) {
                    $where[] = ['create_at', '>=', $stime];
                }
                if (!empty($etime)) {
                    $where[] = ['create_at', '<=', $etime];
                }
            }
            if (!empty($getData['keyword'])){
                $where[] = ['op_name|action_title' , 'like' , '%' . $getData['keyword'] . '%'];
            }
            $option['where'] = $where;
            $result = Services::System()->systemLog($option);
            api_result($result);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    /**
     * 首页数据统计
     */
    public function sys_home()
    {
        $result = Services::System()->sysHome($this->adminUser['mer_id']);
        api_result($result);
    }

    /**
     * 首页商户统计
     */
    public function sys_merchant_home()
    {
        $date = input('get.');
        $this->validate($date, MerchantStatisticValid::class . '.statistic');
        $result = Services::System()->sysMerchantHome(
            $this->adminUser['mer_id'],
            $date['date']
        );
        api_result($result);
    }
    /**
     * 充值金额列表
     * @return void
     */
    public function recharge_money(): void
    {
        if (env('app_mode_release', true)) {
            $list = config('system.recharge_money');
        } else {
            $list = [
                ['id' => '1', 'money' => 1],
                ['id' => '2', 'money' => 2],
                ['id' => '3', 'money' => 3],
                ['id' => '4', 'money' => 4],
                ['id' => '5', 'money' => 5],
                ['id' => '6', 'money' => 6],
            ];
        }
        if (!empty($list)) {
            foreach ($list as &$row) {
                $row['title'] = sprintf("%d元直充（实际到账%.2f元）", $row['money'], $row['money'] - ($row['money'] * RECHARGE_RATE));
            }
        }
        api_result($list);
    }
}
